#pragma once
#include "Log.hpp"
#include "Socket.hpp"
using namespace SocketModule;
using ioservice_t = std::function<void(std::shared_ptr<Socket> &sock, InetAddr &client)>;

class TcpServer : public NoCopy
{
public:
    TcpServer(uint16_t port, ioservice_t service)
        : _port(port), _listensockptr(std::make_unique<TcpSocket>()), _is_running(false), _service(service)
    {
        _listensockptr->BuildTcpSocketMethod(port);
    }

    void Start()
    {
        _is_running = true;
        while (_is_running)
        {
            InetAddr client;                             // 客户端
            auto sock = _listensockptr->Accept(&client); // 返回服务端套接字信息

            if (sock == nullptr)
            {
                continue;
            }

            pid_t pid = fork();
            if (pid > 0)
            {
                // 关闭服务端套接字
                sock->Close();
                waitpid(pid, nullptr, 0);
            }

            else if (pid == 0)
            {
                // 关闭监听端套接字
                _listensockptr->Close();
                if (fork() > 0)
                {
                    exit(OK);
                }
                // 执行对应任务
                _service(sock, client);
            }

            else
            {
                LOG(LogLevel::ERROR) << "procrss fail";
                exit(FORK_ERR);
            }
        }
        _is_running = false;
    }
    ~TcpServer() {}

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listensockptr; // 监听端套接字
    bool _is_running;
    ioservice_t _service;
};